package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.ArticleBehaviorRedisPrefixConstants;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.common.util.JsonUtils;
import com.heima.model.behavior.dtos.ArticleBehaviorShowDTO;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.pojo.ApUserFollow;
import com.heima.user.service.ApUserFollowService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 * APP用户关注信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-03-22
 */
@Service
public class ApUserFollowServiceImpl extends ServiceImpl<ApUserFollowMapper, ApUserFollow> implements ApUserFollowService {

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 关注
     *
     * @param dto
     */
    @Override
    public void follow(UserRelationDto dto) {
        //获取当前用户id
        Integer userId = UserThreadLocalUtils.getUserIdAndCheckLogin();
        // 用户必须登录后才能进行关注
        if (userId <= 0) {
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 保存或修改回显数据
        this.saveOrUpdateForShow(dto, userId);
        // 保存或删除写库数据
        this.saveOrDeleteForFollow(dto, userId);


    }

    /**
     * 保存或删除写库数据
     *
     * @param dto
     * @param userId
     */
    private void saveOrDeleteForFollow(UserRelationDto dto, Integer userId) {
        String key = ArticleBehaviorRedisPrefixConstants.BEHAVIOR_FOLLOW_PREFIX + ":" + userId;
        // 如果是取消关注, 则删除redis中的数据
        if (dto.getOperation() == 1) {
            redisTemplate.opsForHash().delete(key, dto.getArticleId() + "");
        } else if (dto.getOperation() == 0) {
            // 如果是关注, 则新增
            redisTemplate.opsForHash().put(key, dto.getArticleId() + "", JSON.toJSONString(dto));
        }
    }

    /**
     * 保存或修改回显数据
     *
     * @param dto
     * @param userId
     */
    private void saveOrUpdateForShow(UserRelationDto dto, Integer userId) {
        String key = ArticleBehaviorRedisPrefixConstants.BEHAVIOR_SHOW_PREFIX + ":" + userId;
        //构建Redis查询，查询Redis中是否有这样一个数据
        String json = (String) redisTemplate.opsForHash().get(key, dto.getArticleId() + "");
        //如果redis中没有这个数据,则新增
        if (StringUtils.isEmpty(json) || JsonUtils.toBean(json, ArticleBehaviorShowDTO.class) == null) {
            //文章回显的dto
            ArticleBehaviorShowDTO redisDTO = new ArticleBehaviorShowDTO();
            // 关注
            redisDTO.setIsfollow(dto.getOperation() == 0);
            //上传redis
            redisTemplate.opsForHash().put(key, dto.getArticleId() + "", JSON.toJSONString(redisDTO));
        } else {
            //redis中有这个数据
            ArticleBehaviorShowDTO redisDTO = JsonUtils.toBean(json, ArticleBehaviorShowDTO.class);
            // 如果等于0 则为关注, 设置状态为true, 不为0 则为取消关注, 设置状态为false
            redisDTO.setIsfollow(dto.getOperation() == 0);
            redisTemplate.opsForHash().put(key, dto.getArticleId() + "", JSON.toJSONString(redisDTO));
        }
    }
}
